AddCSLuaFile( "cl_init.lua" );
AddCSLuaFile( "shared.lua" );

include( "shared.lua" );

function ENT:SpawnFunction( ply, tr )

	if( !tr.Hit ) then return end
	
	local pos = tr.HitPos + tr.HitNormal * 16;
	
	local ent = ents.Create( self.ClassName );
	ent:SetPos( pos );
	ent:Spawn();
	ent:Activate();
	
	return ent;
	
end

function ENT:Initialize()
	
	self:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" );
	self:PhysicsInit( SOLID_VPHYSICS );
	self:SetMoveType( MOVETYPE_VPHYSICS );
	self:SetSolid( SOLID_VPHYSICS );
	
	local phys = self:GetPhysicsObject();
	if( phys and phys:IsValid() ) then
		
		phys:Wake();
		
	end
	
	C.ClearLinks( self );
	
end

function ENT:PhysicsCollide( data, phy )
	
	if( data.HitEntity == GetWorldEntity() ) then return end
	
	local enttab = ents.FindInSphere( self:GetPos(), 256 );
	
	for _, v in pairs( enttab ) do
		
		if( table.HasValue( C.NoGravApplied, v:GetClass() ) or v.Cosmic ) then
			
			constraint.RemoveAll( v );
			
			if( v:GetPhysicsObject() and v:GetPhysicsObject():IsValid() ) then
				
				v:GetPhysicsObject():EnableMotion( true );
				
				local dist = v:GetPos() - self:GetPos();
				v:GetPhysicsObject():SetVelocity( dist:Normalize() * 2000 );
				
			end
			
		end
		
	end
	
	self:Explode();
	
end

function ENT:Explode()
	
	local exp = ents.Create( "env_explosion" );
		exp:SetKeyValue( "spawnflags", 128 );
		exp:SetPos( self:GetPos() );
	exp:Spawn();
	exp:Fire( "explode", "", 0 );
	
	self:Remove();
	
end

function ENT:CheckLinks()
	
	for k, v in pairs( self.Links ) do
		
		if( !v or !v:IsValid() ) then
			
			table.remove( self.Links, k );
			continue;
			
		end
		
		if( v:GetPos():Distance( self:GetPos() ) > 1024 ) then
			
			table.remove( self.Links, k );
			
			self:EmitSound( Sound( "weapons/stunstick/spark" .. tostring( math.random( 1, 3 ) ) .. ".wav" ) );
			
		end
		
	end
	
end

function ENT:Think()
	
	self:CheckLinks();
	
end